using UnityEngine;
using UnityEngine.AI;

//士兵类
public class SoldierObj : MonoBehaviour
{
    GameObject VFX;
    NavMeshAgent navMeshAgent;
    NavPathLineRenderer navPathLineRenderer;
    Animator animator;
    [HideInInspector] public GameObject target;
    public int attack = 10;//攻击力
    public float attackDistance = 2f;//攻击距离
    void Start()
    {
        VFX = transform.GetChild(0).gameObject;
        VFX.SetActive(false);

        navMeshAgent = GetComponent<NavMeshAgent>();
        animator = GetComponent<Animator>();
        navPathLineRenderer = GetComponent<NavPathLineRenderer>();
    }

    void Update()
    {
        if (target == null) {
            SetAttack(false);
        }
    }

    public void Attack()
    {
        //瞬间面向目标
        // transform.LookAt(target.transform.position);
        SmoothLookAt();

        SetRun(false);
        SetAttack(true);
    }

    //平滑看向目标
    void SmoothLookAt()
    {
        // 计算目标方向
        Vector3 direction = target.transform.position - transform.position;

        // 忽略Y轴差异（如果是2D或水平旋转）
        direction.y = 0;

        // 计算目标旋转
        Quaternion targetRotation = Quaternion.LookRotation(direction);

        // 平滑插值旋转
        transform.rotation = Quaternion.Slerp(
            transform.rotation,
            targetRotation,
            10f * Time.deltaTime
        );
    }

    public void SetSelSelf(bool isSelect)
    {
        VFX.SetActive(isSelect);
    }

    public void Move(Vector3 point, GameObject target)
    {
        this.target = target;
        navPathLineRenderer.StartDraw(point);
    }

    public void SetRun(bool isRun)
    {
        animator.SetBool("isRun", isRun);
    }

    public void SetAttack(bool isAttack)
    {
        animator.SetBool("isAttack", isAttack);
    }

    //收集资源
    public void DoCollect()
    {
        if (target == null) return;
        if (target.GetComponent<Collectable>())
        {
            target.GetComponent<Collectable>().ChangeHealth(-attack);
        }
    }
}